package com.bot.adms.controller.apply;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bot.adms.model.vo.ApplyInfoVo;
import com.bot.adms.service.impl.ApplyServiceImpl;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 删除投放申请控制层
 * @author: 刘威林
 */
@WebServlet("/apply/delete")
public class DeleteApplyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //修改字符集
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        String msg= null;
        int code = 200;
        boolean success = false;

        try {
            //1.获取要查看的审核记录id
            String idStr;
            //2.参数验证
            //判断是否传入id数据
            if(req.getParameter("id") != null && !req.getParameter("id").isEmpty()){
                idStr = req.getParameter("id");
            }else{
                code = 500;
                msg = "id必须存在";
                return;
            }

            //判断是否为数字
            Long id;
            try{
                id = Long.parseLong(idStr);
            }catch (NumberFormatException e){
                code = 500;
                msg = "id必须为数值类型";
                return;
            }

            //4.调用业务逻辑
            ApplyServiceImpl applyService = new ApplyServiceImpl();
            //查询是否存在
            try {
                ApplyInfoVo applyInfo = applyService.getApply(id);
            } catch (Exception e) {
                code = 500;
                msg = "数据不存在";
                return;
            }


            //删除
            Boolean result = applyService.deleteApply(id);

            if (result){
                msg="删除成功";
                success = true;
                code = 200;
            }else {
                msg="删除失败";
                success = false;
                code = 500;
            }
        } catch (NumberFormatException e) {
            code = 500;
            msg = "服务器异常，请稍后再试";
            success = false;
            e.printStackTrace();
        } finally {
            //组装JSON
            jsonObject.put("success", success);
            jsonObject.put("code", code);
            jsonObject.put("msg", msg);


            //将json转成字符串
            String json = JSON.toJSONString(jsonObject);
            //将json转换为字符串并返回
            ServletOutputStream out = resp.getOutputStream();
            out.write(json.getBytes("UTF-8"));
            out.flush();
            out.close();
        }

    }
}
